package com.sbox.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;

import com.sbox.album.R;
import com.sbox.album.model.AlbumContext;
import com.sbox.album.model.AlbumManager;
import com.sbox.album.model.PictureInfo;
import com.sbox.util.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class PicGridView extends GridView {
	private PictureAdapter mAdapter = null;
	private String mFolder = null;
	private PictureInfo[] mPics = null;
	private int mLastLoadImage = -1;
	
	public PicGridView(Context context) {
		super(context);
		init();
	}

	public PicGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}


	public PicGridView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);		
		init();
	}
	
	private void init()
	{
		this.setDrawingCacheEnabled(false);
		this.setOnItemClickListener(mPicClickListener);
	}
	
	public void loadImages(String folder)
	{
		mFolder = folder;
		mLastLoadImage = -1;

		mPics = AlbumManager.listPictures(mFolder);
		mAdapter = new PictureAdapter(this.getContext());
		mAdapter.addPictures( mPics );
		
		this.setAdapter(mAdapter);
	}
	
	public void loadImages(PictureInfo[] pics)
	{
		mPics = pics;
		mAdapter = new PictureAdapter(this.getContext());
		mAdapter.addPictures( mPics );
		
		this.setAdapter(mAdapter);
	}
	
	public PictureInfo[] getSelectedPictures() {
		List<PictureInfo> selPics = new ArrayList<PictureInfo>();
		PictureInfo[] pics = null;
		int count = 0;
		
		for( PictureInfo pic: mPics ) {
			if( pic.isSelected() )
				selPics.add(pic);
		}
		
		count = selPics.size();
		pics = new PictureInfo[count];
		for( int i=0; i<count; i++ ) {
			pics[i] = selPics.get(i);
		}
		
		return pics;
	}

	private void loadImage(String fileName, int position, ImageView v, int width, int height)
	{
		ImageLoaderItem item = null;
		ImageLoaderTask task = null;
		
		//bugbug: Android GridList may refresh the same item multiple times in short time.
		if( position == mLastLoadImage ) {			
			return;
		}
		
		item = new ImageLoaderItem();
		item.mFileName = fileName;
		item.mGridView = this;
		item.mPosition = position;
		item.mImageView = v;
		item.mWdith = width;
		item.mHeight = height;
		
		task = new ImageLoaderTask(item);		
		for( int i=0; i<3; i++ ) {
			try { 
				task.execute(null);
			} catch(RejectedExecutionException e) {
				Utils.sleep(200);
				continue;
			}
			break;
		}
		
		if( mLastLoadImage == -1 )
			mLastLoadImage = position;
	}
	
	public AdapterView.OnItemClickListener mPicClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			boolean selected = false;
			
			PictureInfo pic = (PictureInfo) PicGridView.this.getItemAtPosition(position);
			if( pic == null )
				return;
			
			selected = pic.isSelected();
			selected = !selected;
			
			PicImageView picView = (PicImageView)view;
			picView.setSelected(selected);
			pic.setSelected(selected);
		}
	}; 
	
	public class PictureAdapter extends BaseAdapter {
		private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();
		private Context mContext = null;
		private LayoutInflater mInflater = null;
		private int mWidth = 60;
		private int mHeight = 60;
		
		public PictureAdapter(Context c)
		{
			mContext = c;
			mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		public void setPictureSize(int width, int height) {
			mWidth = width;
			mHeight = height;
		}
			
		public void addPictures(PictureInfo[] pics)
		{
			if( pics == null )
				return;
			
			for( PictureInfo pic : pics )
				mPictures.add(pic);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
	
			return mPictures.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mPictures.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {		
			PictureInfo pic = null;
			//RelativeLayout layout = null;
			//ImageView imgView = null;
			PicImageView picView = null;
			Bitmap bmp = null;
					
			pic = mPictures.get(position);
			if( pic == null )
				return null;
			
			if( convertView != null )					
				picView = (PicImageView)convertView;
			else
				picView = (PicImageView)mInflater.inflate(R.layout.pic_item, null);
			picView.setSelected(pic.isSelected());
			
			//bmp = AlbumContext.getCacheManager().findImage(pic.getFileName().hashCode());
			bmp = AlbumContext.getCacheManager().findImage(position);			
			if( bmp != null ) {
				picView.setImage(bmp);
			} else {
				picView.setImage(null);						
				PicGridView.this.loadImage(pic.getFileName(), position, picView.getImageView(), mWidth, mHeight);
			}
			
			return picView;
		}	
	}
	
	public class ImageLoaderItem
	{
		public String mFileName;
		public GridView mGridView;
		public int mPosition;
		public ImageView mImageView;
		public int mWdith;
		public int mHeight;
	}
	
	public class ImageLoaderTask extends AsyncTask<ImageLoaderItem, Integer, Integer>{
		private ImageLoaderItem mItem = null;
		private Bitmap mBitmap = null;
		
		public ImageLoaderTask(ImageLoaderItem item)
		{
			mItem = item;
		}
		
		@Override
		protected Integer doInBackground(ImageLoaderItem... params) {	
			
			int sleep = PicGridView.this.mPics.length*5;
			
			if( sleep > 1000 )
				sleep = 500;
			//maybe don't need to load, scrolling...
			if( PicGridView.this.mPics.length > 100 )
			{
				Utils.sleep(sleep);
			}
			
			int first = PicGridView.this.getFirstVisiblePosition();		
			
			if( mItem.mPosition < first-6 || mItem.mPosition >= first + 24 )
				return 0;
			
			//mBitmap = PictureUtils.createSmallPicture(mItem.mFileName, mItem.mWdith, mItem.mHeight, 50);
			mBitmap = AlbumContext.getAlbumCache().getThumbBitmap(mItem.mFileName);
			
			return 0;
		}
		
		
		protected void onPostExecute(Integer result) {

			int first = PicGridView.this.getFirstVisiblePosition() ;
			int last = PicGridView.this.getLastVisiblePosition();
			
			if( mBitmap == null )
				return;
			
			if( mItem.mPosition >= first && mItem.mPosition <= last )
				mItem.mImageView.setImageBitmap(mBitmap);
			
			//PicGridView.this.cacheImage(mItem.mPosition, mBitmap);
			AlbumContext.getCacheManager().cacheImage(mItem.mPosition, mBitmap);
	    }
	}

}
